<?php

function links_urlCheckReplace($url, $string_check = TRUE)
{
	$return_url = preg_replace(
		array("/javascript:/si", "/about:/si", "/vbscript:/si"),
		array("java script :",   "about :",    "vb script :"),
		$url
	);
	if ($string_check == TRUE) {
		if (preg_match("/[\\x0-\\x1f]|[\\x7f]/", $url)) {
			die('Invalid URL');
		}
	//	$return_url = preg_replace("/[^a-zA-Z0-9\/:\.\+@_-]/", '', $url);
	}
	return $return_url;
}


function check_URI($uri, $no_check = FALSE)
{
	$status_code = 0;

	if (isset($_POST['no_check_uri']) && $_POST['no_check_uri'] == 1 && $no_check) {
		$status_code = 297;//TODO
	} else {

		if (! empty($uri)) {
			// TODO NIHON-GO Domain
			if (preg_match("/[^0-9a-zA-Z_:=&%\.\/\?-]/", $uri)) {
				if (preg_match("/^http[s]{0,1}:\/\//i",$uri)) {
					$status_code = 298;//TODO
				}
			} else {

				if (preg_match("/^http:\/\//i",$uri)) {
					$status_code = https_request($uri);
				} else if (preg_match("/^https:\/\//i", $uri)) {
					if (function_exists('stream_get_wrappers') && in_array('https', stream_get_wrappers())) {
						$status_code = https_request($uri);
					} else {
						$status_code = 299;//TODO
					}
				}
			}
		}
	
	}

	$status_code = intval($status_code);
	return $status_code;
}


function check_by_snoopy($uri)
{
	$response_code = 0;

	require_once XOOPS_ROOT_PATH . '/class/snoopy.php';
	$snoopy = New Snoopy;
	@$snoopy->fetch($uri);
	if (@$snoopy->response_code) {
		$res = explode(' ', $snoopy->response_code);
	}
	if (isset($res[1])) {
		$response_code = intval($res[1]);
	}

	return $response_code;
}

function https_request($uri, $sec=10, $mobile=0)
{
	$response_code = 0;

	if (intval(PHP_VERSION) < 5) {
		// snoopy
		$response_code = check_by_snoopy($uri);
	} else {

		// PEAR
		if (! class_exists('HTTP_Request')) {
			require_once XOOPS_TRUST_PATH .'/modules/links/class/PEAR/Request.php';
		}

		$option = array(
			"timeout"        => $sec , 
			"allowRedirects" => TRUE ,
			"maxRedirects"   => 3 ,
		);

		$http = new HTTP_Request($uri, $option);

		$response = $http->sendRequest();

		if (! PEAR::isError($response)) {
			$response_code = $http->getResponseCode();
		} else {
			$response_code = check_by_snoopy($uri);
		}

	}

	return $response_code ;
}

// smarty modifier
function links_substr($string, $start, $length, $ext = '...')
{
	if (strlen($string) > $length) {
		if (function_exists('mb_strlen') && function_exists('mb_strcut')) {
			$string = mb_strcut($string, $start, $length) . $ext;
		} else {
			$string = substr($string, $start, $length) . $ext;
		}
	}
	return $string;
}

/** breadcrumbs
 *
**/
if (! function_exists('assign_get_breadcrumbs_by_tree')) {
	function assign_get_breadcrumbs_by_tree( $table, $id_col, $pid_col, $name_col, $id_val, $url_fmt, $paths=array() )
	{
		$db =& Database::getInstance() ;

		$sql = "SELECT `$pid_col`,`$name_col` FROM ".$table." WHERE `$id_col`=".intval($id_val) ;
		$result = $db->query( $sql ) ;
		if( $db->getRowsNum( $result ) == 0 ) return $paths ;
		list( $pid , $name ) = $db->fetchRow( $result ) ;

		$paths = array_merge( array( array(
			'name' => htmlspecialchars( $name , ENT_QUOTES, _CHARSET) ,
			'url'  => sprintf( $url_fmt , $id_val ) ,
		) ) , $paths ) ;

		return assign_get_breadcrumbs_by_tree( $table, $id_col, $pid_col, $name_col, $pid, $url_fmt, $paths ) ;
	}
}


if (! function_exists('smarty_function_my_make_uri')) {
	function smarty_function_my_make_uri($params, &$smarty)
	{
		$mydirname  = isset($params['mydirname'])  ? preg_replace('/[^a-zA-Z0-9_-]/',   '', $params['mydirname']) : '';
		$controller = isset($params['controller']) ? preg_replace('/[^a-zA-Z0-9_-]/',   '', $params['controller']): 'index';
		$method     = isset($params['method'])     ? preg_replace('/[^a-zA-Z0-9_-]/',   '', $params['method'])    : 'index';
		$option     = isset($params['option'])     ? preg_replace('/[^a-zA-Z0-9\._-]/', '', $params['option'])    : '';// ARRAY
		$p_val1     = isset($params['p_val1'])     ? preg_replace('/[^a-zA-Z0-9_-]/',   '', $params['p_val1'])    : '';
		$p_val2     = isset($params['p_val2'])     ? preg_replace('/[^a-zA-Z0-9_-]/',   '', $params['p_val2'])    : '';
		$p_val3     = isset($params['p_val3'])     ? preg_replace('/[^a-zA-Z0-9_-]/',   '', $params['p_val3'])    : '';
		$p_key1     = isset($params['p_key1'])     ? preg_replace('/[^a-zA-Z0-9_-]/',   '', $params['p_key1'])    : '';
		$p_key2     = isset($params['p_key2'])     ? preg_replace('/[^a-zA-Z0-9_-]/',   '', $params['p_key2'])    : '';
		$p_key3     = isset($params['p_key3'])     ? preg_replace('/[^a-zA-Z0-9_-]/',   '', $params['p_key3'])    : '';
		$no_esc     = isset($params['no_esc'])     ? "&": "&amp;";

		$uri = XOOPS_URL . '/';

		if ($option['url_approach'] < 3) {
			$uri .= 'modules/';
		}
		$uri .= $mydirname;

		$plus_uri = '';
		if ($option['url_approach'] > 0) {

			//segment approach
			if ($option['url_approach'] == 1) {
				$plus_uri .= '/index.php';
			}

			if ($controller != 'index') {
				$plus_uri .= '/' . $controller;
			}

			if ($method != 'index') {
				$plus_uri .= '/' . $method;
			}

			if ($p_val1 !== '' && $p_key1 != '') {
				$plus_uri .= '/' . $p_val1 ;
			}

			if ($p_val2 !== '' && $p_key2 != '') {
				$plus_uri .= '/' . $p_val2 ;
			}

			if ($p_val3 !== '' && $p_key3 != '') {
				$plus_uri .= '/' . $p_val3 ;
			}

			if ($plus_uri == '/index.php') {
				$plus_uri = '/';
			} elseif (!empty($option['url_suffix'])) {
				$plus_uri .= empty($plus_uri) ? '/': $option['url_suffix'];
			}

			$uri .= $plus_uri;

		} else {

			//query approach
			$plus_uri .= '/index.php';

			if ($controller != 'index') {
				$plus_uri .= '?c=' . $controller;
			}

			if ($method != 'index') {
				$joint = (strpos($plus_uri, '?') > 0) ? $no_esc: '?';
				$plus_uri .= $joint ."m=" . $method;
			}

			if ($p_val1 != '' && $p_key1 != '') {
				$joint = (strpos($plus_uri, '?') > 0) ? $no_esc: '?';
				$plus_uri .= $joint . $p_key1 . '=' . $p_val1 ;
			}

			if ($p_val2 != '' && $p_key2 != '') {
				$plus_uri .= $no_esc . $p_key2 . '=' . $p_val2 ;
			}

			if ($p_val3 != '' && $p_key3 != '') {
				$plus_uri .= $no_esc . $p_key3 . '=' . $p_val3 ;
			}

			if ($plus_uri == '/index.php') {
				$plus_uri = '/';
			}

			$uri .= $plus_uri;

		}

		return $uri;
	}

}



function links_xoops_template_touch($tpl_id, $mydirname = 'links', $clear_old = true)
{
	if (defined('XOOPS_CUBE_LEGACY')) {
		return TRUE;
	}

	$tpl = new XoopsTpl();

	$tpl->register_function('my_make_uri', 'smarty_function_my_make_uri');
	if (
		!file_exists(XOOPS_ROOT_PATH . '/class/smarty/plugins/function.d3comment.php') &&
		!file_exists(XOOPS_TRUST_PATH . '/libs/smartyplugins/function.d3comment.php') 
		)
	{
		require_once realpath(dirname(__FILE__)) . '/../class/smartyplugins/function.d3comment.php';
		$tpl->register_function('d3comment', 'smarty_function_d3comment');
	}
	if (
		!file_exists(XOOPS_ROOT_PATH .'/class/smarty/plugins/function.xoopsdhtmltarea.php') && 
		!file_exists(XOOPS_TRUST_PATH .'/libs/smartyplugins/function.xoopsdhtmltarea.php')
	) {
		require_once realpath(dirname(__FILE__)) . '/../class/smartyplugins/function.xoopsdhtmltarea.php';
		$tpl->register_function('xoopsdhtmltarea', 'smarty_function_xoopsdhtmltarea');
	}
	$tpl->assign(array('mydirname' => $mydirname)); // for fix warning in X2


	$tpl->force_compile = true;
	$tplfile_handler =& xoops_gethandler('tplfile');
	$tplfile =& $tplfile_handler->get($tpl_id);

	if ( is_object($tplfile) ) {
		$file = $tplfile->getVar('tpl_file');
		if ($clear_old) {
			$tpl->clear_cache('db:'.$file);
			$tpl->clear_compiled_tpl('db:'.$file);
		}
		$tpl->fetch('db:'.$file);

		return true;
	}
	return false;
}

